//
//  EmoticomKeyBoardView.swift
//  EmoticonKeyBoard
//
//  Created by Arvin on 15/11/20.
//  Copyright © 2015年 Arvin. All rights reserved.
//

import UIKit

private let toolbarHeight = 36
private let emojiViewCell = "emojiViewCell"

class EmoticonKeyBoardView: UIView {
    
    // MARK: toolBarItem 点击事件
    @objc private func didClickToolBarItem(item: UIBarButtonItem) {
        
        let indexPath = NSIndexPath(forItem: 0, inSection: item.tag)
        EmojiView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
    }

    // MARK: 回调闭包
    var finished: ((emoticon: Emoticon) -> ())?
    
    private lazy var emoticonPackages: [EmoticonPackages] = EmoticonManeger.shareEmoticonManager.emoticonPackages
    
    // 在init中设置frame, 外部就不需要设置了
    init(finished:((emoticon: Emoticon) -> ())?) {
        // 保存闭包
        self.finished = finished
        
        let rect = CGRectMake(0, 0, 0, 220)
        super.init(frame: rect)
        
        setupToolBar()
        setupEmojiView()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    let itemSetting: [String] = ["默认", "Emoji", "花浪浪"]
    var items: [UIBarButtonItem] = [UIBarButtonItem]()
    
    private lazy var toolBar: UIToolbar = UIToolbar()
    // MARK: emojiCollectcionView
    private lazy var EmojiView: UICollectionView = {
        
        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        // itemSize
        let w = UIScreen.mainScreen().bounds.width / 7
        layout.itemSize = CGSizeMake(w, w)
        let margin = (self.bounds.height - (3 * w) - CGFloat(toolbarHeight)) / 4
        layout.sectionInset = UIEdgeInsetsMake(margin, 0, margin, 0)
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        let emojiView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
        
        emojiView.dataSource = self
        emojiView.delegate = self
        
        emojiView.registerClass(EmojiViewCell.self, forCellWithReuseIdentifier: emojiViewCell)
        emojiView.showsHorizontalScrollIndicator = false
        emojiView.bounces = false
        emojiView.pagingEnabled = true
        emojiView.backgroundColor = UIColor.whiteColor()
        return emojiView
    }()
}

extension EmoticonKeyBoardView: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let emo = emoticonPackages[indexPath.section].emoticonsList[indexPath.item]
        finished?(emoticon: emo)
    }
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {

        return emoticonPackages.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return emoticonPackages[section].emoticonsList.count 
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(emojiViewCell, forIndexPath: indexPath) as! EmojiViewCell
        
        cell.emoticon = emoticonPackages[indexPath.section].emoticonsList[indexPath.item]
        return cell
    }
    
}


extension EmoticonKeyBoardView {
    
    private func setupEmojiView() {
        addSubview(EmojiView)
        
        EmojiView.snp_makeConstraints { (make) -> Void in
            make.top.left.right.equalTo(self)
            make.bottom.equalTo(toolBar.snp_top)
        }
        
    }
    
    private func setupToolBar() {
        addSubview(toolBar)
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self)
            make.height.equalTo(toolbarHeight)
        }
        
        var index = 0
        for title in itemSetting {
            let item = UIBarButtonItem(title: title, style: .Plain, target: self, action: "didClickToolBarItem:")
            items.append(item)
            items.last?.tag = index++
            
            let flexiabelSpace = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(flexiabelSpace)
        }
        
        items.removeLast()
        toolBar.items = items
        toolBar.tintColor = UIColor.lightGrayColor()
    }
    
}

class EmojiViewCell: UICollectionViewCell {
    
    var emoticon: Emoticon? {
        didSet {
            enojiBtn.setImage(emoticon?.imagePng, forState: .Normal)

            // 设置系统的表情, 需要将16进制字符串转成表情
            enojiBtn.setTitle(emoticon?.codeStr ?? "", forState: UIControlState.Normal)

            if (emoticon?.isDelete == true) {
                enojiBtn.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
            }
        }
    }
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        setupEmojiBtn()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupEmojiBtn() {

        contentView.addSubview(enojiBtn)
        enojiBtn.backgroundColor = UIColor.whiteColor()
        // 设置btn的fram
        enojiBtn.frame = self.bounds
        // 设置enojeBtn的内缩
        enojiBtn.frame = CGRectInset(self.bounds, 3, 3)
                
    }
    
    private lazy var enojiBtn: UIButton = {
        let b = UIButton()
        // 通过设置tiele的大小设置系统emoji的大小
        b.titleLabel?.font = UIFont.systemFontOfSize(32)
        // 禁用btn的交互事件, 把处理事件交给cell
        b.userInteractionEnabled = false
        return b
    }()
}


